package cn.xingzhe.monster.user.infrastructure.repository.impl;

import cn.xingzhe.monster.user.domain.model.CaptchaModel;
import cn.xingzhe.monster.user.domain.enums.CaptchaTypeEnum;
import cn.xingzhe.monster.user.domain.repository.CaptchaRepository;
import cn.xingzhe.monster.user.infrastructure.persistence.converter.CaptchaEntityConverter;
import cn.xingzhe.monster.user.infrastructure.persistence.entity.CaptchaEntity;
import cn.xingzhe.monster.user.infrastructure.repository.CaptchaMongoRepository;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * MongoDB 验证码仓储实现
 * 内部操作 CaptchaEntity，对外返回 CaptchaModel
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
@Component
public class MongoCaptchaRepository implements CaptchaRepository {

    private final CaptchaMongoRepository mongoRepository;

    public MongoCaptchaRepository(CaptchaMongoRepository mongoRepository) {
        this.mongoRepository = mongoRepository;
    }

    @Override
    public Optional<CaptchaModel> findByKeyAndType(String key, CaptchaTypeEnum type) {
        return mongoRepository.findByKeyAndType(key, type)
                .map(CaptchaEntityConverter::toModel);
    }

    @Override
    public CaptchaModel save(CaptchaModel captcha) {
        CaptchaEntity entity = CaptchaEntityConverter.toEntity(captcha);
        CaptchaEntity savedEntity = mongoRepository.save(entity);
        return CaptchaEntityConverter.toModel(savedEntity);
    }

    @Override
    public void deleteByKeyAndType(String key, CaptchaTypeEnum type) {
        mongoRepository.deleteByKeyAndType(key, type);
    }

    @Override
    public void deleteExpiredCaptchas() {
        // MongoDB TTL 索引会自动删除过期文档，此方法可以用于手动清理（如果需要）
        // 实际实现可以查询当前时间之前的验证码并删除
    }

}

